<?php
/**
 * 省份，城市，地区获取
 * Class AreaModule
 */
class AreaModule extends SiteMode {
    /** @return AreaModule */
    public static function init() {
        return parent::init();
    }

    // 新建
    function add($data){
        $data['site_id']=$this->siteId;
        return $this->db->insert('base_address',$data)?(int)$this->db->insertId():-1;
    }

    //修改消息
    function modify($data){
        return $this->db->update('base_address',$data['id'],$data)==1;
    }

    function delete($id){
        return $this->db->delete('base_address',$id)==1;
    }

    function getDetail($id){
        $sql="SELECT * FROM `base_address` WHERE `id`=?";
        return $this->db->getOne($sql,$id);
    }

    public function getAll($pid=0){
        $data=$this->getSon($pid);
        foreach(new ArrayIterator($data) as $k=>$v) {
            $data[$k]['children']=$this->getAll((int)$v['id']);
        }
        return $data;
    }

    // 获取某一个地点所有下一级内容
    function getSon($pid=0){
        $sql="SELECT `id`,`name`,`pid`,`level` FROM `base_address` WHERE pid= ? and site_id=?";
        return $this->db->getAll($sql, (int)$pid, $this->siteId);
    }

    // 指定省所有市
    function getInfo($ids){
        $sql="SELECT `id`,`name`,`pid`,`level` FROM `base_address` WHERE site_id=? and ".$this->db->getIdCondition($ids);
        $re =$this->db->getAll($sql, $this->siteId);
        return is_array($ids)? $re: reset($re);
    }
    //由地址ID获取 上一级地址
    public function getFather($id){
        $data = $this->getInfo($id);
        $sql = "select * from `base_address` where id=? and site_id=?";
        return $this->db->getOne($sql,(int)$data['pid'], $this->siteId);
    }

    // 根据一个地址，获取所有上一级内容
    function getFullAddress($id){
        $addressData=array();
        $re= $this->getInfo($id);
        while(isset($re)){
            $addressData[]= $re;
            $id=$re['id'];
            $re= $this->getFather($id);
        }
        return array_reverse($addressData);
    }
} 